﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Xsl;
using Ext.Net;

/// <summary>
/// 2011.11.08 박승한 - Ext컨트롤 이용 베스트 싸이트 작성
/// </summary>
public partial class _Default : System.Web.UI.Page
{
    #region == Page_Load == 

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            #region == ISPOSTBACK 사용자 정보 셋팅 (향후 세션&쿠키&GET) ==
            if (!IsPostBack)
            {
                //회사정보가 없을경우 에러
                if (Session["COMPANY"] == null)
                {
                    Response.Redirect("Error.aspx?key=1");
                }

                this.Window2.Hide();
                this.Window4.Hide();//마감 수정요청

                if (Request["USERID"] == null)
                {
                    this.Window10.ShowModal();
                }
                else
                {
                    this.Window10.Hide();

                    string template = "<br /><b>LOGIN SUCCESS</b><br /><br />Username: {0}<br />Password: {1}";
                    string username = this.txtUsername.Text;
                    string password = this.txtPassword.Text;
                    //this.lblMessage.Html = string.Format(template, username, password);

                    this.btnLoginSate.Html = string.Format(template, username, password);
                }


                //콤보박스 스토어 채우기
                this.SetALLCombo_S();
                this.SetAddCombo();

                

            }
            #endregion

            #region == Determines if the current HttpRequest is an Ext.NET Ajax Request. ==

            if (!X.IsAjaxRequest)
            {

                //분석 필요
                string text = @"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.";

                this.ResourceManager1.RegisterClientScriptBlock("text", string.Format("var text=\"{0}\";", text));

                foreach (Portlet portlet in Ext.Net.Utilities.ControlUtils.FindControls<Portlet>(this.Page))
                {
                    if (!portlet.ID.Equals("Portlet1"))
                    {
                        portlet.Html = "={text}";
                        portlet.Padding = 5;
                    }
                }

            }
            #endregion

        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

    #endregion

    private void SetAddCombo()
    {
        this.cbxAddMat.Items.Add(new ListItem("주요자재현황", "A"));
        this.cbxAddMat.Items.Add(new ListItem("발주대상관리 리스트", "B"));
        this.cbxAddMat.Items.Add(new ListItem("업체별발주단가(표준디비)", "C"));
        //this.cbxAddMat.Items.Add(new ListItem("공종계획", "D")); //세양안씀
        this.cbxAddMat.SelectedIndex = 0;

        this.cbxAddEqp.Items.Add(new ListItem("장비현황 리스트", "A"));
        this.cbxAddEqp.Items.Add(new ListItem("장비코드 리스트", "B"));
        this.cbxAddEqp.SelectedIndex = 0;

        this.cbxAddTrans.Items.Add(new ListItem("운송현황 리스트", "A"));
        this.cbxAddTrans.Items.Add(new ListItem("운송코드 리스트", "B"));
        this.cbxAddTrans.SelectedIndex = 0;

        //임시주석처리
        //this.cbxAddCost.Items.Add(new ListItem("전도금", "A"));
        //this.cbxAddCost.Items.Add(new ListItem("법인카드", "B"));
        //this.cbxAddCost.SelectedIndex = 0;

        
    }


    #region == btnLogin_Click(로그인 클릭) ==
    protected void btnLogin_Click(object sender, DirectEventArgs e)
    {
        try
        {
            string username = this.txtUsername.Text.Trim();
            string password = this.txtPassword.Text.Trim();
            DataSet dsReturn = this.Login(username, password);
            switch (dsReturn.Tables[0].Rows[0][0].ToString())
            {
                case "0": //로그인 성공
                    this.Window10.Hide();
                    string template = "&nbsp;&nbsp;&nbsp;&nbsp;[ 로그인중입니다. : <b>{0}</b> 님 ]  ";

                    //this.lblMessage.Html =  string.Format(template, dsReturn.Tables[0].Rows[0]["NAME"].ToString());
                    this.btnLoginSate.Text = string.Format(template, dsReturn.Tables[0].Rows[0]["NAME"].ToString());
                    Session["JUMIN_NM"] = dsReturn.Tables[0].Rows[0]["NAME"].ToString();
                    Session["USER_CODE"] = dsReturn.Tables[0].Rows[0]["USER_CODE"].ToString();
                    //this.btnLoginSate.Text = "로그아웃";
                    //this.btnLoginSate.Icon = Icon.Lock;
                    this.hdnJm.Value= Session["JUMIN_NO"] = dsReturn.Tables[0].Rows[0]["JUMIN_NO"].ToString();

                    #region ==/프로젝트 코드 넣기==
                    //프로젝트 코드 넣기

                    //노드1레벨 확장
                    //NodeLoad("0", string.Empty);
                    Session["PROJ_CD"] = null;
                    this.TreePanel1.ExpandNode("0");
                    this.Window2.Show();

                    if (Session["USER_CODE"].ToString().Equals("A"))
                    {
                        this.Button35.Show();
                        this.btnChoiceAdd_Click(this.btnConfirmView, new DirectEventArgs(new ParameterCollection()));
                    }
                    else
                    {
                        this.Button35.Hide();
                    }
                   // Session["PROJ_CD"] = "003612";
                    //리스트뷰 바인딩
                    //this.SetListViewData(Session["PROJ_CD"].ToString());
                    
                    #endregion
                    //string strProjCd = string.Empty;
                    //if (Session["PROJ_CD"] != null)
                    //{
                    //    strProjCd = Session["PROJ_CD"].ToString();
                    //}
                    

                    break;
                case "1": //사용자 없음
                    this.ShowAlertMessage("확인", "사용자번호와 비밀번호를 확인하십시오!!");
                    break;
                case "2": //비밀번호 불일치
                default:
                    this.ShowAlertMessage("확인", " 패스워드를 확인해주세요!!");

                    break;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    /// <summary>
    /// 로그인 수행
    /// </summary>
    /// <param name="pJmin"></param>
    /// <param name="pPassword"></param>
    /// <returns></returns>
    private DataSet Login(string pJmin,string pPassword)
    {
        DataSet dsReturn = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            dsReturn = oService.Select_W_LOGIN_P2(pJmin, pPassword);

        }
        return dsReturn;
    }

    #endregion
  
    #region == GetBaseInfoData (기본정보 데이터 가져오기) ==

    private DataTable GetBaseInfoData(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_D_FPD200T_S(pProjId, pDt);

        }
        return ds.Tables[0];
    }
    #endregion

    #region == 전체그리드 에 바인딩할 dataset 가져오기 ==
    /// <summary>
    /// 전체그리드 에 바인딩할 dataset 가져오기
    /// </summary>
    /// <param name="pProjId"></param>
    /// <param name="pDt"></param>
    /// <returns></returns>
    private DataSet GetGrid_ALL_DataSet(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_ALL_GRID_S(pProjId, pDt);

        }
        return ds;

    }
    #endregion

    #region == panel grid1(인원현황) 에 바인딩할 datatable 가져오기 ==
    /// <summary>
    /// panel grid1(인원현황) 에 바인딩할 datatable 가져오기
    /// </summary>
    /// <param name="pProjId"></param>
    /// <param name="pDt"></param>
    /// <returns></returns>
    private DataTable GetGrid1_DataTable(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_FPD220T_P(pProjId, pDt);

        }

        return ds.Tables[0];

    }
    #endregion

    #region == pane3 grid1(경비현황) 에 바인딩할 datatable 가져오기 ==
    /// <summary>
    /// panel grid1(인원현황) 에 바인딩할 datatable 가져오기
    /// </summary>
    /// <param name="pProjId"></param>
    /// <param name="pDt"></param>
    /// <returns></returns>
    private DataTable GetGridGB_DataTable(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_D_DAYEATPAY_S(pProjId, pDt);

        }
        return ds.Tables[0];

    }
    #endregion

    #region ==(외주관리) 에 바인딩할 datatable 가져오기 ==
    /// <summary>
    /// panel grid1(인원현황) 에 바인딩할 datatable 가져오기
    /// </summary>
    /// <param name="pProjId"></param>
    /// <param name="pDt"></param>
    /// <returns></returns>
    private DataTable GetGridOI_DataTable(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_D_FPD370T_S(pProjId, pDt);

        }
        return ds.Tables[0];

    }
    #endregion

    #region ==(외주관리 DETAIL) 에 바인딩할 datatable 가져오기 ==
    /// <summary>
    /// panel grid1(외주관리 DETAIL) 에 바인딩할 datatable 가져오기
    /// </summary>
    /// <param name="pProjId"></param>
    /// <param name="pDt"></param>
    /// <returns></returns>
    private DataTable GetGridOI2_DataTable(string pProjId, string pDt,string pSeqNo)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_D_FPD370T_DETAIL_S(pProjId, pDt, pSeqNo);

        }
        return ds.Tables[0];

    }
    #endregion
    
    

    #region == panel grid2(자재) 에 바인딩할 datatable 가져오기 ==
    /// <summary>
    /// panel grid1(인원현황) 에 바인딩할 datatable 가져오기
    /// </summary>
    /// <param name="pProjId"></param>
    /// <param name="pDt"></param>
    /// <returns></returns>
    private DataTable GetGrid2DataTable(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_FPD240T_P(pProjId, pDt);

        }
        return ds.Tables[0];

    }
    #endregion

    #region == btnBaseInfoSave_Click(기본정보 저장버튼 클릭) ==

    protected void btnBaseInfoSave_Click(object sender, DirectEventArgs e)
    {
        try
        {
            string strCloseYn = Session["CLOSE_YN"].ToString();
            if (!CheckCloseYn())
                return;

            if ((sender as Button).ID == "Button35")
            {
                strCloseYn = "Y";
            }

            string strProjCd = string.Empty;
            string strDt = string.Empty;
            if (Session["PROJ_CD"] != null)
            {
                strProjCd = Session["PROJ_CD"].ToString();
            }
            if (Session["DT"] != null)
            {
                strDt = Session["DT"].ToString();
            }

            string strPROJ_CD = strProjCd;
            string strDT = strDt;
            string strPROJ_NM = this.txtPROJ_NM.Text;
            string strREG_NAME = this.txtREG_NAME.Text;
            string strCFM_NAME = this.txtCFM_NAME.Text;
            string strLOC = this.txtLOC.Text;
            string strH_TEMP = string.Empty;//this.txtL_TEMP.Text;
            string strL_TEMP = this.txtL_TEMP.Text;
            string strRAINFALL = string.Empty;//this.txtDT.Text;
            string strSNOWFALL = string.Empty;//this.txtDT.Text;
            string strTO_WORK = this.txtTO_WORK.Text;
            string strNE_WORK = this.txtNE_WORK.Text;

            int nResult = 0;
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {
                #region == 저장 Status 표시 ==
                //저장 메시지
                X.Msg.Show(new MessageBoxConfig
                {
                    Message = "저장 중입니다..잠시만 기다려주십시오..",
                    ProgressText = "생성중...",
                    Width = 300,
                    Wait = true,
                    WaitConfig = new WaitConfig { Interval = 150 },
                    IconCls = "ext-mb-download",
                    AnimEl = Store1.ClientID
                });
                #endregion

                nResult = oService.UPDATE_D_FPD200T_U1(strPROJ_CD, strDT, strPROJ_NM, strREG_NAME, strCFM_NAME, strLOC, strH_TEMP, strL_TEMP, strRAINFALL, strSNOWFALL, strTO_WORK, strNE_WORK, strCloseYn);

                #region == 저장확인 메시지 ==
                //저장확인 메시지
                if (nResult > 0)
                {
                    this.SetListViewData(Store1, null);
                    this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '저장 완료되었습니다.'); }, 500);");
                    this.Window4.Hide();
                }
                else
                {
                    this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '저장에 실패했습니다. 잠시후 다시 시도해 주십시오.'); }, 500);");
                }
                #endregion
            }
          
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    #endregion

    #region == ListView1_SelectionChange(일자/마감 리스트뷰 선택 이벤트) ==

    /// <summary>
    /// 일자/마감 리스트뷰 선택 이벤트 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ListView1_SelectionChange(object sender, DirectEventArgs e)
    {
        try
        {  
            //프로젝트 코드 가져오기
            string strProjCd = string.Empty;
            if (Session["PROJ_CD"] != null)
            {
                strProjCd = Session["PROJ_CD"].ToString();
            }

            //날짜, 마감여부 가져오기 (Session,hidden Setting)
            string[] strParams = this.GetJsonToString(e.ExtraParams["Values"]);
            if (strParams.Length < 2) return;
            string strDt = strParams[1];

            //세션셋팅
            Session["DT"] = strParams[1];
            Session["CLOSE_YN"] = strParams[5];
            //히든셋팅
            this.hdnPROJ_CD.Value = strProjCd;
            this.hdnDT.Value = strDt;

            //수정요청 버튼 셋팅 
            this.btnReqModify.Hidden = !strParams[5].Equals("Y");

            #region == 기본정보 바인딩 ==
            //기본정보
            this.SetBaseInfoInit();
            DataTable dtBase = this.GetBaseInfoData(strProjCd, strDt);

            if (dtBase == null || dtBase.Rows.Count == 0) return;

            this.txtPROJ_NM.Text = dtBase.Rows[0]["PROJ_NM"].ToString();
            this.txtREG_NAME.Text = dtBase.Rows[0]["REG_NAME"].ToString();

            //작성자명이 없을경우 로그인 사용자를 뿌려준다.
            this.txtREG_NAME.Text = this.txtREG_NAME.Text.Trim().Length.Equals(0) ?
                (Session["JUMIN_NM"] == null ? "" : Session["JUMIN_NM"].ToString()) : this.txtREG_NAME.Text;

            this.txtCFM_NAME.Text = dtBase.Rows[0]["CFM_NAME"].ToString();
            this.txtDT.Text = dtBase.Rows[0]["DT"].ToString();
            this.txtLOC.Text = dtBase.Rows[0]["LOC"].ToString();
            //this.txtPROJ_NM.Text = dtBase.Rows[0]["H_TEMP"].ToString();
            this.txtL_TEMP.Text = dtBase.Rows[0]["L_TEMP"].ToString();
            //this.txtPROJ_NM.Text = dtBase.Rows[0]["RAINFALL"].ToString();
            //this.txtPROJ_NM.Text = dtBase.Rows[0]["SNOWFALL"].ToString();
            this.txtTO_WORK.Text = dtBase.Rows[0]["TO_WORK"].ToString();
            this.txtNE_WORK.Text = dtBase.Rows[0]["NE_WORK"].ToString();
            //this.txtPROJ_NM.Text = dtBase.Rows[0]["PIC"].ToString();
            #endregion

            //string strGroupTitle = string.Format("{0}   -   {1}", this.txtPROJ_NM.Text, this.txtDT.Text);

            //this.Panel1.Title = strGroupTitle;

           
            #region == 그리드 바인딩 ==

            

            //그리드 전체 데이터
            DataSet dsSource = this.GetGrid_ALL_DataSet(strProjCd, strDt);

            #region == 인원현황 ==
            this.Store2.DataSource = dsSource.Tables[0];
            this.Store2.DataBind();
            this.GrpViewPeople.GroupTextTpl = "인원현황 합계 보기";
            #endregion

            #region == 자재현황 ==
            this.Store4.DataSource = dsSource.Tables[1];
            this.Store4.DataBind();
            this.GrpViewMat.GroupTextTpl = "자재현황 합계 보기";
            
            #endregion

            #region == 장비현황 ==
            this.StrEqp.DataSource = dsSource.Tables[2];
            this.StrEqp.DataBind();
            this.GrpViewEqp.GroupTextTpl = "장비현황 합계 보기";
            #endregion

            #region == 공종계획 ==
            this.Store6.DataSource = dsSource.Tables[3];
            this.Store6.DataBind();
            //this.GroupingView2.GroupTextTpl = "합계 보기";

            //합계계산
            if (dsSource.Tables[4].Rows.Count > 0)
            {

                this.lblSum11.Text = dsSource.Tables[4].Rows[0]["SUM_AMT"].ToString();
                this.lblSum12.Text = dsSource.Tables[4].Rows[0]["AMT"].ToString();
                this.lblSum13.Text = dsSource.Tables[4].Rows[0]["PERCENT"].ToString();

                this.lblSum21.Text = dsSource.Tables[4].Rows[0]["SUM_AMT1"].ToString();
                this.lblSum22.Text = dsSource.Tables[4].Rows[0]["AMT_S"].ToString();
                this.lblSum23.Text = dsSource.Tables[4].Rows[0]["PERCENT_S"].ToString();
            }


            #endregion

            #region == 운송 ==
            this.StrTrans.DataSource = dsSource.Tables[5];
            this.StrTrans.DataBind();
            this.GrpViewTrans.GroupTextTpl = "운송현황 합계 보기";
            #endregion

            #region == 경비==
            this.Store5.DataSource = dsSource.Tables[6];
            this.GridPanel3.DataBind();
            this.GroupingView1.GroupTextTpl = "경비현황 합계 보기";


            this.Store10.DataSource = dsSource.Tables[7];
            this.GridPanel8.DataBind();
            this.GroupingView6.GroupTextTpl = "경비현황 합계 보기";

            this.Store9.DataSource = dsSource.Tables[8];
            this.GridPanel7.DataBind();
            this.GroupingView5.GroupTextTpl = "경비현황 합계 보기";
            #endregion

            #region == 지출결의서==
            #endregion

            #region == 외주관리 ==
            this.Store7.DataSource = dsSource.Tables[10];
            this.GridPanel5.DataBind();
            this.GroupingView3.GroupTextTpl = "합계 보기";

            if (dsSource.Tables[10].Rows.Count > 0)
            {
                this.hdnOISEQ_NO.Value = dsSource.Tables[10].Rows[0]["SEQ_NO"].ToString();
                this.Store_RefreshData(this.Store8, null);
            }
            else
                this.Store8.RemoveAll();
            #endregion

            #endregion

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    #region == 마감된 공사일지 재수정 요청 확인 버튼 클릭 ==
    protected void btnReqReDayWrite_Click(object sender, DirectEventArgs e)
    {
        try
        {
            //요청사유를 입력해야 합
            if (this.TextField21.Text.Trim().Length == 0)
            {
                this.ShowAlertMessage("확인", "요청사유를 입력해 주십시오");
                this.TextField21.Focus();
                return;
            }


            //이미 요청중인지 확인
            string json = e.ExtraParams["Values"];
            string strREQ_JUMIN_NO = string.Empty;
            string strCONFIRM_YN = string.Empty;

            Dictionary<string, string>[] companies = JSON.Deserialize<Dictionary<string, string>[]>(json);


            foreach (Dictionary<string, string> row in companies)
            {
                foreach (KeyValuePair<string, string> keyValuePair in row)
                {
                    if (keyValuePair.Key == "REQ_JUMIN_NO")
                        strREQ_JUMIN_NO = keyValuePair.Value;

                    if (keyValuePair.Key == "CONFIRM_YN")
                        strCONFIRM_YN = keyValuePair.Value;
                }
            }
            if (!string.IsNullOrEmpty(strREQ_JUMIN_NO) && strCONFIRM_YN.Equals("N"))
            {
                this.ShowAlertMessage("확인", " 이미 요청중입니다.");
                return;
            }


            string strAS_PROJ_CD = string.Empty;
            string strAS_DT = string.Empty;
            string strAS_REQ_JUMIN_NO = string.Empty;
            string strAS_CONFIRM_JUMIN_NO = string.Empty;
            object dateAS_REQ_DATE;
            object dateAS_CONFIRM_DATE;
            string strAS_CONFIRM_YN = string.Empty;
            string strAS_REQ_MSG = string.Empty;
            string strAS_CONFIRM_MSG = string.Empty;

            //프로젝트 번호
            strAS_PROJ_CD = Session["PROJ_CD"] == null ? string.Empty : Session["PROJ_CD"].ToString();
            strAS_DT = Session["DT"] == null ? string.Empty : Session["DT"].ToString();
            strAS_REQ_JUMIN_NO = Session["JUMIN_NO"] == null ? string.Empty : Session["JUMIN_NO"].ToString();
            strAS_CONFIRM_JUMIN_NO = string.Empty;
            dateAS_REQ_DATE = DateTime.Now;
            dateAS_CONFIRM_DATE = null;
            strAS_CONFIRM_YN = "N";
            strAS_REQ_MSG = this.TextField21.Text;
            strAS_CONFIRM_MSG = string.Empty;


            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {
                #region == 저장 Status 표시 ==
                //저장 메시지
                X.Msg.Show(new MessageBoxConfig
                {
                    Message = "요청 중입니다..잠시만 기다려주십시오..",
                    ProgressText = "생성중...",
                    Width = 300,
                    Wait = true,
                    WaitConfig = new WaitConfig { Interval = 150 },
                    IconCls = "ext-mb-download",
                    AnimEl = Store1.ClientID
                });
                #endregion

                string strResult = oService.INSERT_DAYWRITE_LOG_I(strAS_PROJ_CD, strAS_DT, strAS_REQ_JUMIN_NO, strAS_CONFIRM_JUMIN_NO, dateAS_REQ_DATE, dateAS_CONFIRM_DATE, strAS_CONFIRM_YN, strAS_REQ_MSG, strAS_CONFIRM_MSG);

                #region == 저장확인 메시지 ==
                int nResult = 0;
                if (int.TryParse(strResult,out nResult))
                {

                    //저장확인 메시지
                    if (nResult > 0)
                    {
                        this.SetListViewData(Store1, null);
                        this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '요청 완료되었습니다.'); }, 500);");
                        this.Window4.Hide();
                    }
                    else
                    {
                        this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '요청에 실패했습니다. 잠시후 다시 시도해 주십시오.'); }, 500);");
                    }
                }
                else
                {
                    this.ShowAlertMessage("확인", strResult);
                }
                #endregion
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    


    #region == Store_RefreshData ==

    protected void Store_RefreshData(object sender, StoreRefreshDataEventArgs e)
    {
        Store oStore = sender as Store;
        string strProjCd = string.Empty;
        string strDt = string.Empty;
        if (Session["PROJ_CD"] != null)
        {
            strProjCd = Session["PROJ_CD"].ToString();
        }
        if (Session["DT"] != null)
        {
            strDt = Session["DT"].ToString();
        }
        if (oStore is Store)
        {
            //기타작업
            switch (oStore.ID)
            {
                case "Store2": //인원현황
                    oStore.DataSource = this.GetGrid1_DataTable(strProjCd, strDt);
                    oStore.DataBind();
                    break;
                case "Store4": //자재현황
                    oStore.DataSource = this.GetGrid2DataTable(strProjCd, strDt);
                    oStore.DataBind();
                    break;
                case "StrEqp"://장비현황
                    oStore.DataSource = this.GetGrid_DataTable_Eqp(strProjCd, strDt);
                    oStore.DataBind();
                    break;
                case "Store6"://공종현황
                    oStore.DataSource = this.GetGrid_DataTable_Kong(strProjCd, strDt, string.Empty);
                    oStore.DataBind();
                    break;
                case "StrTrans"://운송연황
                    oStore.DataSource = this.GetGrid_DataTable_Trans(strProjCd, strDt);
                    oStore.DataBind();
                    break;
                case "Store5": //경비현황
                    oStore.DataSource = this.GetGridGB_DataTable(strProjCd, strDt);
                    oStore.DataBind();
                    break;
                case "Store7": //외주관리
                    oStore.DataSource = this.GetGridOI_DataTable(strProjCd, strDt);
                    oStore.DataBind();
                    break;
                case "Store8": //외주관리
                    if (e != null)
                    {
                        hdnOISEQ_NO.Value = e.Parameters[0].Value;
                    }
                    oStore.DataSource = this.GetGridOI2_DataTable(strProjCd, strDt, hdnOISEQ_NO.Value.ToString());
                    oStore.DataBind();
                    break;
                default:
                    break;
            }
        }
    }
    #endregion

    #region == Store_Submit(xml,xls,csv Save) ==
    protected void Store_Submit(object sender, StoreSubmitDataEventArgs e)
    {
        try
        {
            string format = this.FormatType.Value.ToString();

            XmlNode xml = e.Xml;

            this.Response.Clear();

            switch (format)
            {
                case "xml":
                    string strXml = xml.OuterXml;
                    this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml");
                    this.Response.AddHeader("Content-Length", strXml.Length.ToString());
                    this.Response.ContentType = "application/xml";
                    this.Response.Write(strXml);

                    break;
                case "xls":
                    this.Response.ContentType = "application/vnd.ms-excel";
                    this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xls");
                    XslCompiledTransform xtExcel = new XslCompiledTransform();
                    xtExcel.Load(Server.MapPath("Excel.xsl"));
                    xtExcel.Transform(xml, null, Response.OutputStream);

                    break;
                case "csv":
                    this.Response.ContentType = "application/octet-stream";
                    this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.csv");
                    XslCompiledTransform xtCsv = new XslCompiledTransform();
                    xtCsv.Load(Server.MapPath("Csv.xsl"));
                    xtCsv.Transform(xml, null, Response.OutputStream);
                    break;
            }

            this.Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    #region == Store_AfterEdit(Store 셀 수정후 발생) ==

    [DirectMethod(Namespace = "CompanyX",ShowMask=true)]
    public void AfterEdit(int id, string field, string oldValue, string newValue, object customer)
    {
        //string message = "<b>Property:</b> {0}<br /><b>Field:</b> {1}<br /><b>Old Value:</b> {2}<br /><b>New Value:</b> {3}";

        //// Send Message...
        //X.Msg.Notify("Edit Record #" + id.ToString(), string.Format(message, id, field, oldValue, newValue)).Show();

        //this.GridPanel1.Store.Primary.CommitChanges();
    }
    #endregion

    

    #region == Store_BeforeChanged(Store1 데이터가 변경되기전, 즉 Store에 들어오는 변경데이터를 파라미터로 보내옴) ==
    /// <summary>
    /// 실제 저장하는 이벤트
    /// Store1_BeforeChanged(Store1 데이터가 변경되기전, 즉 Store에 들어오는 변경데이터를 파라미터로 보내옴)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Store_BeforeChanged(object sender, BeforeStoreChangedEventArgs e)
    {
        int nResult = 0;
        DataSet dsSave = null;
        try
        {
            Store oStore = sender as Store;
            if (oStore != null)
            {
                if (!CheckCloseYn())
                {
                    oStore.RejectChanges();
                    return;
                }

                dsSave = this.GetXmlDocumentToSaveDataSet(e.DataHandler.XmlData);

                #region == 저장 Status 표시 ==
                //저장 메시지
                X.Msg.Show(new MessageBoxConfig
                {
                    Message = "저장 중입니다..잠시만 기다려주십시오..",
                    ProgressText = "Saving...",
                    Width = 300,
                    Wait = true,
                    WaitConfig = new WaitConfig { Interval = 150 },
                    IconCls = "ext-mb-download",
                    //AnimEl = Store1.ClientID
                });
                #endregion

                using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
                {
                    switch (oStore.ID)
                    {
                        case "Store2": //인원현황
                            nResult = oService.SAVE_D_FPD220T_IU(dsSave);
                            break;
                        case "Store4": //자재현황
                            nResult = oService.SAVE_D_FPD240T_IU(dsSave);
                            break;
                        case "StrEqp": //장비현황
                            nResult = oService.SAVE_D_FPD230T_IUD(dsSave);
                            break;
                        case "Store6": //공종현황
                            nResult = oService.SAVE_D_FPD210T_1_IUD(dsSave);
                            break;
                        case "StrTrans": //운송현황
                            nResult = oService.SAVE_DAYTRANSPORT1_IUD(dsSave);
                            break;
                        case "Store5": //경비현황
                            nResult = oService.SAVE_D_DAYEATPAY_IUD(dsSave);
                            break;
                        case "Store8" :
                        case "Store7": //외주현황 

                            int nY = 0;
                            foreach (DataColumn dc in dsSave.Tables[0].Columns)
                            {
                                if (dc.Caption == "SEQ_NO")
                                {
                                    nY++;
                                    break;
                                }

                            }
                            if (nY == 0)
                            {
                                dsSave.Tables[0].Columns.Add("SEQ_NO");
                                foreach (DataRow dr in dsSave.Tables[0].Rows)
                                {
                                    dr["SEQ_NO"] = this.hdnOISEQ_NO.Value.ToString();
                                }
                            }

                            nResult = oService.SAVE_D_FPD370T_D(dsSave);
                            break;
                            

                    }
                }

                #region == 저장확인 메시지 ==
                //저장확인 메시지
                if (nResult > 0)
                {
                    this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '저장되었습니다.'); }, 500);");
                }
                #endregion
            }
            else
            {
               //Store가 아닐경우 pass
            }

        }
        catch (Exception ex)
        {
            this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '저장에 실패했습니다. 잠시후 다시 시도해주십시오.'); }, 500);");
            throw ex;
        }

    }

    /// <summary>
    /// Store에서 넘어오는Xmldocument를 저장 Dataset으로 반환
    /// </summary>
    /// <param name="pXd"></param>
    /// <returns></returns>
    private DataSet GetXmlDocumentToSaveDataSet(XmlDocument pXd)
    {
        DataSet dsReturn = new DataSet() ;

        using (System.Xml.XmlReader reader = new XmlNodeReader(pXd))
        {
            DataSet dsData = new DataSet();
            dsData.ReadXml(reader);
            reader.Close();
            dsReturn.Tables.Add(dsData.Tables[1].Copy());
            dsReturn.AcceptChanges();
        }
        return dsReturn;
    }

    #endregion

    #region == Store1_BeforeInserted ==
    //This handler will be calling for each inserted record
    protected void Store_BeforeInserted(object sender, BeforeRecordInsertedEventArgs e)
    {
    }
    #endregion

    #region == Store1_BeforeUpdated ==
    //This handler will be calling for each changed record
    protected void Store_BeforeUpdated(object sender, BeforeRecordUpdatedEventArgs e)
    {
    }
    #endregion

    #region == Store1_BeforeDeleted ==
    //This handler will be calling for each deleted record
    protected void Store_BeforeDeleted(object sender, BeforeRecordDeletedEventArgs e)
    {

    }
    #endregion

    #region == Store1_BeforeDeleted ==
    protected void Store_AfterChanged(object sender, AfterStoreChangedEventArgs e)
    {
    }
    #endregion

    #region == btnProjChoose_Click ==
    protected void btnProjChoose_Click(object sender, DirectEventArgs e)
    {
      

        string[] strId = this.GetJsonToString(e.ExtraParams[0].ToString());

        if (strId[1].Equals("none")) //취소일 경우
        {
            if (Session["PROJ_CD"] == null)
            {
                this.ShowAlertMessage("확인", "선택된 프로젝트가 없습니다. 프로젝트를 선택해 주십시오.");
                return;
            }
            else
            {
                this.Window2.Hide();
            }
        }

        string[] strData = strId[1].Split('|');

        if (strData.Length == 5)
        {
            this.hdnPROJ_CD.Value = Session["PROJ_CD"] = strData[3];
            this.btnProjMain.Text = "<b>"+ strData[4] + "</b> (작업중)";

            this.SetListViewData(null,null);

            this.Window2.Hide();
        }
    }

    #endregion


    private DataTable GetGrid_DataTable_Kong(string pProjId, string pDt,string pItemCd)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_D_FPD210T_1_S(pProjId, pDt, string.IsNullOrEmpty(pItemCd) ? "%" : pItemCd);
        }
        return ds.Tables[0];
    }

    #region == btnProjMain_Click ==
    protected void btnProjMain_Click(object sender, DirectEventArgs e)
    {
        if (sender is Button && (sender as Button).ID.Equals("btnProjCancel"))
        {
            if (Session["PROJ_CD"] != null)
            {
                this.Window2.Hide();
            }
            else
            {
                this.ShowAlertMessage("알림", "선택된 프로젝트가 없습니다. 프로젝트를 선택해주십시오.");
            }
        }
        else
        {
            this.Window2.Show();
        }
    }

    #endregion

    protected void DT_NEW_Clicked(object sender, DirectEventArgs e)
    {
        try
        {
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {

                string strProjCd = string.Empty;
                string strDate = string.Empty;
                DataSet ds = null;

                if (Session["PROJ_CD"] != null)
                {
                    strProjCd = Session["PROJ_CD"].ToString();


                    strDate = this.GetJsonToString(e.ExtraParams[0].ToString())[1];
                    strDate = strDate.Split('T')[0].Replace("-", string.Empty).Trim();

                    //오늘날짜보다 이전날짜이면 안되요~~
                    if (int.Parse(DateTime.Now.ToString("yyyyMMdd")) > int.Parse(strDate))
                    {
                        this.ShowAlertMessage("알림", "오늘날짜보다 이전날짜는 새로운 일지를 생성할수 없습니다.");
                        return;
                    }

                    ds = oService.Select_PROJ_CONTRACT_YN_S(strProjCd, strDate);

                    string strFJP005T_CNT = string.Empty;
                    string strDEGREE = string.Empty;
                    string strFPD200T_CNT = string.Empty;
                    string strIS_DT = string.Empty;
                    string strFPD200T_PROJ_CNT = string.Empty;

                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        strFJP005T_CNT = ds.Tables[0].Rows[0]["FJP005T_CNT"].ToString();
                        strDEGREE = ds.Tables[0].Rows[0]["DEGREE"].ToString();
                        strFPD200T_CNT = ds.Tables[0].Rows[0]["FPD200T_CNT"].ToString();
                        strFPD200T_PROJ_CNT = ds.Tables[0].Rows[0]["FPD200T_PROJ_CNT"].ToString();
                        strIS_DT = ds.Tables[0].Rows[0]["IS_DT"].ToString();
                    }

                    //계약이 진행되지 않았거나 계약확정 체크를 하지 않은 프로젝트
                    if (strFJP005T_CNT.Equals("0"))
                    {
                        this.ShowAlertMessage("알림", "계약이 진행되지 않았거나 계약확정 체크를 하지 않은 프로젝트입니다.");
                        return;
                    }

                    //신규공사일지 생성
                    if (strFPD200T_PROJ_CNT.Equals("0"))
                    {
                        this.ShowYesNoMessage("알림", "신규 공사일지를 생성하시겠습니까?", sender, strProjCd, strDate, "C");
                    }
                    else//선택날짜 추가
                    {
                        int nResult = 0;

                        if (strFPD200T_CNT.Equals("0"))
                        {

                            #region == 저장 Status 표시 ==
                            //저장 메시지
                            X.Msg.Show(new MessageBoxConfig
                            {
                                Message = "생성 중입니다..잠시만 기다려주십시오..",
                                ProgressText = "생성중...",
                                Width = 300,
                                Wait = true,
                                WaitConfig = new WaitConfig { Interval = 150 },
                                IconCls = "ext-mb-download",
                                AnimEl = Store1.ClientID
                            });
                            #endregion

                            nResult = oService.INSERT_PROJ_NEW2_DAY_I(strProjCd, strDate);


                            #region == 저장확인 메시지 ==
                            //저장확인 메시지
                            if (nResult > 0)
                            {
                                this.SetListViewData(Store1, null);
                                this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '생성 완료되었습니다.'); }, 500);");
                            }
                            else
                            {
                                this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '실패했습니다. 잠시후 다시 시도해 주십시오.'); }, 500);");
                            }
                            #endregion
                        }
                        else
                        {
                            this.ShowAlertMessage("알림", "이미 작성된 자료가 존재합니다.");
                            return;
                        }
                    }


                    this.Window3.Hide();
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {

        }
    }


    protected void DeleteDiaryForProj(object sender, DirectEventArgs e)
    {
        string strProjCd = string.Empty;
        string strDt = string.Empty;
        string strCloseYn = string.Empty;

        if (Session["PROJ_CD"] != null)
        {
            strProjCd = Session["PROJ_CD"].ToString();
        }
        if (Session["DT"] != null)
        {
            strDt = Session["DT"].ToString();
        }
        if (Session["CLOSE_YN"] != null)
        {
            strCloseYn = Session["CLOSE_YN"].ToString();
        }

        if (strCloseYn.Equals("Y"))
        {
            this.ShowAlertMessage("확인", "마감된 일지입니다. 삭제할수 없습니다.");
            return;
        }

        this.ShowYesNoMessage("알림", "해당 공사일지를 삭제하시겠습니까?", sender, strProjCd, strDt, "D");
    }

    protected void ShhowRequestDayWrite(object sender, DirectEventArgs e)
    {
        string strProjCd = string.Empty;
        string strDt = string.Empty;
        string strCloseYn = string.Empty;
        string strJuminNM = string.Empty;

        if (Session["PROJ_CD"] != null)
        {
            strProjCd = Session["PROJ_CD"].ToString();
        }
        if (Session["DT"] != null)
        {
            strDt = Session["DT"].ToString();
        }
        if (Session["CLOSE_YN"] != null)
        {
            strCloseYn = Session["CLOSE_YN"].ToString();
        }
        if (Session["JUMIN_NM"] != null)
        {
            strJuminNM = Session["JUMIN_NM"].ToString();
        }

        if (!strCloseYn.Equals("Y"))
        {
            this.ShowAlertMessage("확인", "마감되지 않은 데이터 입니다. 요청할수 없습니다.");
            return;
        }

        this.TextField22.Text = string.Format("{0}-{1}-{2}", strDt.Substring(0, 4), strDt.Substring(4, 2), strDt.Substring(6, 2));
        this.TextField23.Text = strJuminNM;  //요청자
        this.TextField31.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm");  //요청일시
        this.TextField21.Text = string.Empty;
        this.TextField21.Focus();
        this.Window4.Show();
    }


    [DirectMethod(ShowMask=true,Msg="삭제중입니다...")]
    public static string DeleteDiaryForProj(string pProjCd, string pDt)
    {
        string strResult = "완료되었습니다.";
        int nResult = 0;

        try
        {
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {

                string strDate = pDt;
                

                //string[] strParams = param.Replace("[{", "").Replace(":", "").Replace(",", "").Replace("}]", "").Split(new string[] { "\"" }, StringSplitOptions.RemoveEmptyEntries);
                //strDate = strParams[1];


                nResult = oService.DELETE_PROJ_DAY_D(pProjCd, strDate);


                #region == 저장확인 메시지 ==
                //저장확인 메시지
                if (nResult > 0)
                {
                    strResult = "삭제되었습니다.";
                    //this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '생성 완료되었습니다.'); }, 500);");
                }
                else
                {
                    strResult = "실패했습니다. 잠시후 다시 시도해 주십시오.";
                    //this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '실패했습니다. 잠시후 다시 시도해 주십시오.'); }, 500);");
                }
                #endregion
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return strResult;
    }




    [DirectMethod]
    public static string CreateNewDiaryForProj(string pProj_Cd,string pDt)
    {
        string strResult = "완료되었습니다.";

        try
        {
            using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
            {
                DataSet ds = null;

                ds = oService.Select_PROJ_CONTRACT_YN_S(pProj_Cd, pDt);

                string strFJP005T_CNT = string.Empty;
                string strDEGREE = string.Empty;
                string strFPD200T_CNT = string.Empty;
                string strIS_DT = string.Empty;
                string strFPD200T_PROJ_CNT = string.Empty;

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    strFJP005T_CNT = ds.Tables[0].Rows[0]["FJP005T_CNT"].ToString();
                    strDEGREE = ds.Tables[0].Rows[0]["DEGREE"].ToString();
                    strFPD200T_CNT = ds.Tables[0].Rows[0]["FPD200T_CNT"].ToString();
                    strFPD200T_PROJ_CNT = ds.Tables[0].Rows[0]["FPD200T_PROJ_CNT"].ToString();
                    strIS_DT = ds.Tables[0].Rows[0]["IS_DT"].ToString();
                }


                if (strDEGREE == "1")
                {
                    X.Msg.Alert("알림", "계약완료 차수는 하나만 가능합니다.", new JFunction { Fn = "showResult" }).Show();
                    strResult = "공사일지 생성에 실패했습니다.";
                }
                else if (strDEGREE == "0")
                {
                    X.Msg.Alert("알림", "계약완료 차수를 체크해주세요!.", new JFunction { Fn = "showResult" }).Show();
                    strResult = "공사일지 생성에 실패했습니다.";
                }
                else
                {
                    int nResult = 0;

                    //공사일지 최초생성
                    //#region == 저장 Status 표시 ==
                    ////저장 메시지
                    //X.Msg.Show(new MessageBoxConfig
                    //{
                    //    Message = "생성 중입니다..잠시만 기다려주십시오..",
                    //    ProgressText = "생성중...",
                    //    Width = 300,
                    //    Wait = true,
                    //    WaitConfig = new WaitConfig { Interval = 150 },
                    //    IconCls = "ext-mb-download",
                    //    AnimEl = Store1.ClientID
                    //});
                    //#endregion

                    nResult = oService.INSERT_PROJ_NEW1_DAY_I(pProj_Cd, pDt, strDEGREE);


                    #region == 저장확인 메시지 ==
                    //저장확인 메시지
                    if (nResult > 0)
                    {
                        strResult = "생성 완료되었습니다.";
                        //this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '생성 완료되었습니다.'); }, 500);");
                    }
                    else
                    {
                        strResult = "실패했습니다. 잠시후 다시 시도해 주십시오.";
                        //this.ResourceManager1.AddScript("setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('알림', '실패했습니다. 잠시후 다시 시도해 주십시오.'); }, 500);");
                    }
                    #endregion
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return strResult;
        
    }


    #region Store EQP 장비현황 Store
    //장비
    private DataTable GetGrid_DataTable_Eqp(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_D_FPD230T_S(pProjId, pDt);
        }
        return ds.Tables[0];
    }

    protected void StrEqp_RefreshData(object sender, StoreRefreshDataEventArgs e)
    {
        Store oStore = sender as Store;
        string strProjCd = string.Empty;
        string strDt = string.Empty;
        if (Session["PROJ_CD"] != null)
        {
            strProjCd = Session["PROJ_CD"].ToString();
        }
        if (Session["DT"] != null)
        {
            strDt = Session["DT"].ToString();
        }
        if (oStore is Store)
        {
            oStore.DataSource = this.GetGrid_DataTable_Eqp(strProjCd, strDt);
            oStore.DataBind();
        }
    }

    protected void StrEqp_BeforeChanged(object sender, BeforeStoreChangedEventArgs e)
    {
        if (!CheckCloseYn())
            return;

        using (System.Xml.XmlReader reader = new XmlNodeReader(e.DataHandler.XmlData))
        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            DataSet dsData = new DataSet();
            dsData.ReadXml(reader);
            reader.Close();

            DataSet dsSave = new DataSet();
            DataTable dtSave = new DataTable();
            dsSave.Tables.Add(dsData.Tables[1].Copy());
            dsSave.AcceptChanges();

            int nResult = oService.SAVE_D_FPD220T_IU(dsSave);
        }

    }

    //This handler will be calling for each inserted record
    protected void StrEqp_BeforeInserted(object sender, BeforeRecordInsertedEventArgs e)
    {

    }

    //This handler will be calling for each changed record
    protected void StrEqp_BeforeUpdated(object sender, BeforeRecordUpdatedEventArgs e)
    {

    }

    //This handler will be calling for each deleted record
    protected void StrEqp_BeforeDeleted(object sender, BeforeRecordDeletedEventArgs e)
    {

    }

    protected void StrEqp_AfterChanged(object sender, AfterStoreChangedEventArgs e)
    {

    }

    protected void StrEqp_Submit(object sender, StoreSubmitDataEventArgs e)
    {
        string format = this.FormatType.Value.ToString();

        XmlNode xml = e.Xml;

        this.Response.Clear();

        switch (format)
        {
            case "xml":
                string strXml = xml.OuterXml;
                this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml");
                this.Response.AddHeader("Content-Length", strXml.Length.ToString());
                this.Response.ContentType = "application/xml";
                this.Response.Write(strXml);

                break;
            case "xls":
                this.Response.ContentType = "application/vnd.ms-excel";
                this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xls");
                XslCompiledTransform xtExcel = new XslCompiledTransform();
                xtExcel.Load(Server.MapPath("Excel.xsl"));
                xtExcel.Transform(xml, null, Response.OutputStream);

                break;
            case "csv":
                this.Response.ContentType = "application/octet-stream";
                this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.csv");
                XslCompiledTransform xtCsv = new XslCompiledTransform();
                xtCsv.Load(Server.MapPath("Csv.xsl"));
                xtCsv.Transform(xml, null, Response.OutputStream);

                break;
        }

        this.Response.End();
    }
    #endregion Store Customer 장비현황 Store

    #region Store EQP 운송현황 Store
    //운송
    private DataTable GetGrid_DataTable_Trans(string pProjId, string pDt)
    {
        DataSet ds = null;

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            ds = oService.Select_DAYTRANSPORT1_S(pProjId, pDt);
        }
        return ds.Tables[0];
    }
    #endregion Store Customer 운송현황 Store



    [DirectMethod]
    public static string NodeLoad(string nodeID,string jm)
    {
        Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
        DataSet ds = null;
        if (!string.IsNullOrEmpty(nodeID))
        {
            if (nodeID.Equals("0"))
            {
                using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
                {
                    ds = oService.Select_W_SELPROJ_BY_NODE_S(jm, 1, string.Empty, string.Empty, string.Empty);
                }

                //root
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    AsyncTreeNode asyncNode = new AsyncTreeNode();
                    asyncNode.Text = dr["YEAR"].ToString() + "년";
                    asyncNode.NodeID = dr["YEAR"].ToString();

                    if (!nodes.Contains(asyncNode))
                        nodes.Add(asyncNode);
                }

            }
            else
            {
                string[] strParam = nodeID.Split('|');
                switch (strParam.Length)
                {
                    case 1:

                        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
                        {
                            ds = oService.Select_W_SELPROJ_BY_NODE_S(jm, 2, strParam[0], string.Empty, string.Empty);
                        }

                        //root
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            AsyncTreeNode asyncNode = new AsyncTreeNode();
                            asyncNode.Text = dr["PROJ_CLASS"].ToString();
                            asyncNode.NodeID = dr["YEAR"].ToString() + "|" + dr["PROJ_CLASS"].ToString();

                            if (!nodes.Contains(asyncNode))
                                nodes.Add(asyncNode);
                        }

                        break;
                    case 2:

                        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
                        {
                            ds = oService.Select_W_SELPROJ_BY_NODE_S(jm, 3, strParam[0], strParam[1], string.Empty);
                        }

                        //root
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            AsyncTreeNode asyncNode = new AsyncTreeNode();
                            asyncNode.Text = dr["PROJ_TYPE"].ToString();
                            asyncNode.NodeID = dr["YEAR"].ToString() + "|" + dr["PROJ_CLASS"].ToString() +"|" + dr["PROJ_TYPE"].ToString();

                            if (!nodes.Contains(asyncNode))
                                nodes.Add(asyncNode);
                        }

                        break;
                    case 3:

                        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
                        {
                            ds = oService.Select_W_SELPROJ_BY_NODE_S(jm, 4, strParam[0], strParam[1], strParam[2]);
                        }

                        //root
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            TreeNode treeNode = new TreeNode();
                        
                            treeNode.Text = dr["PROJ_NM"].ToString();
                            treeNode.NodeID = dr["YEAR"].ToString() + "|" + dr["PROJ_CLASS"].ToString() +"|"+ dr["PROJ_TYPE"].ToString()
                                + "|" + dr["PROJ_CD"].ToString() + "|" + dr["PROJ_NM"].ToString();
                            treeNode.Leaf = true;

                            if (!nodes.Contains(treeNode))
                                nodes.Add(treeNode);
                        }

                        break;
                }
            }

            
        }

        return nodes.ToJson();
    }
    

    

    #region == CheckCloseYn(마감된 날짜인지 확인후 메시지 띄우고 리턴) ==

    private bool CheckCloseYn()
    {
        if (Session["CLOSE_YN"] == null)
        {

            this.ShowAlertMessage("확인", "작성일자를 선택해주십시오.");

            return false ;
        }
        if (Session["CLOSE_YN"].ToString().Equals("Y"))
        {
            this.ShowAlertMessage("확인", "마감처리한 일자는 수정/삭제가 불가능합니다.");
            return false;
        }

        return true;
    }
    #endregion    

    #region == SetBaseInfoInit(기본정보 텍스트박스들 초기화) ==

    private void SetBaseInfoInit()
    {
        this.txtPROJ_NM.Text = string.Empty;
        this.txtDT.Text = string.Empty;
        this.txtREG_NAME.Text = string.Empty;
        this.txtCFM_NAME.Text = string.Empty;
        this.txtLOC.Text = string.Empty;
        //this.txtPROJ_NM.Text =string.Empty;
        this.txtL_TEMP.Text = string.Empty;
        //this.txtPROJ_NM.Text = string.Empty;
        //this.txtPROJ_NM.Text =string.Empty;
        this.txtTO_WORK.Text = string.Empty;
        this.txtNE_WORK.Text = string.Empty;
        //this.txtPROJ_NM.Text 

        this.lblSum11.Text = string.Empty;
        this.lblSum12.Text = string.Empty;
        this.lblSum13.Text = string.Empty;
        this.lblSum21.Text = string.Empty;
        this.lblSum22.Text = string.Empty;
        this.lblSum23.Text = string.Empty;

    }
    #endregion   

    #region
    private void SetDetailgridsinit()
    {
        Store2.RemoveAll();
        Store4.RemoveAll();
        StrEqp.RemoveAll();
        Store6.RemoveAll();
        StrTrans.RemoveAll();
        Store5.RemoveAll();
        Store7.RemoveAll();
        Store8.RemoveAll();  
    }
    #endregion

    #region == SetListViewData(일자/마감 리스트뷰 조회) ==

    /// <summary>
    /// 일자/마감 리스트뷰 조회
    /// </summary>
    /// <param name="strProjCd"></param>
    protected void SetListViewData(object sender, StoreRefreshDataEventArgs e)
    {
        string strProjCd = string.Empty;
        if (Session["PROJ_CD"] != null)
        {
            strProjCd = Session["PROJ_CD"].ToString();
        }

        this.SetBaseInfoInit();
        this.SetDetailgridsinit();

        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {

            DataSet dsSource = oService.Select_D_DAYWRITE_DAY_S(strProjCd);
            if (dsSource != null )
            {
                //List<object> data = new List<object>(dsSource.Tables[0].Rows.Count);
                //foreach (DataRow dr in dsSource.Tables[0].Rows)
                //{
                //    data.Add(new
                //    {
                //        DT = dr["DT"].ToString(),
                //        DT_V = dr["DT_V"].ToString(),    
                //        CLOSE_YN = dr["CLOSE_YN"].ToString(),
                //        CHA = dr["CHA"].ToString()
                //    });
                //}

                this.ListView1.SelectedRow = null;
                var store = this.ListView1.GetStore();
                store.DataSource = dsSource.Tables[0];
                store.DataBind();
                
                if (dsSource.Tables[0].Rows.Count > 0)
                {
                    this.ListView1.Select(new int[] { 0 });
                }

            }

            
        }
    }
    #endregion   

    #region == 콤보박스 바인딩 모음 ==

    #region == 콤보박스 전체 ==
    /// <summary>
    /// 콤보박스 전체
    /// </summary>
    private void SetALLCombo_S()
    {
        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            DataSet dsSrouce = oService.Select_ALL_COMBO_S();

            //업무
            this.Store3.DataSource = dsSrouce.Tables[0];
            this.Store3.DataBind();

            //거래처
            this.StrBiz.DataSource = dsSrouce.Tables[1];
            this.StrBiz.DataBind();

            //관련증빙
            this.StrProof.DataSource = dsSrouce.Tables[2];
            this.StrProof.DataBind();

            //자재/수목
            this.SetStoreItemGubun();

        }
    }
    #endregion

    #region == 업무 ==
    /// <summary>
    /// 업무 콤보박스를 위한 스토어 데이터 채우기
    /// </summary>
    private void SetStoreDDDWCLASS_NM_S()
    {
        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            DataSet dsgr1_Name = oService.Select_DDDWCLASS_NM_S();
            this.Store3.DataSource = dsgr1_Name.Tables[0];
            this.Store3.DataBind();
        }
    }
    #endregion

    #region == 거래처 ==
    /// <summary>
    /// 거래처 콤보박스를 위한 스토어 데이터 채우기
    /// </summary>
    private void SetStoreDDDWCLASS_NM_S2()
    {
        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            DataSet dsSource = oService.Select_DDDWCLASS_NM_S2();
            this.StrBiz.DataSource = dsSource.Tables[0];
            this.StrBiz.DataBind();
        }
    }
    #endregion

    #region == 관련증빙 ==
    /// <summary>
    /// 관련증빙 콤보박스를 위한 스토어 데이터 채우기
    /// </summary>
    private void SetStoreDDDW_461_S()
    {
        using (EmdisBest.WebService.Service oService = new EmdisBest.WebService.Service())
        {
            DataSet dsSource = oService.Select_DDDW_461_S();
            this.StrProof.DataSource = dsSource.Tables[0];
            this.StrProof.DataBind();
        }
    }
    #endregion

    #region == 자재/수목 ==
    private void SetStoreItemGubun()
    {
        DataTable dtItem = new DataTable();
        dtItem.Columns.Add("CODE");
        dtItem.Columns.Add("NAME");
        dtItem.Rows.Add(new object[] { "M", "자재" });
        dtItem.Rows.Add(new object[] { "S", "수목" });
        dtItem.Rows.Add(new object[] { "", "기타" });
        dtItem.AcceptChanges();
        this.StrItemGubun.DataSource = dtItem;
        this.StrItemGubun.DataBind();
    }
    #endregion

    #endregion

    #region == Jason To String ==
    /// <summary>
    /// Json을 string[]으로...
    /// </summary>
    /// <param name="pJson"></param>
    /// <returns></returns>
    private string[] GetJsonToString(string pJson)
    {
        return pJson.Replace("[{", "").Replace(":", "").Replace(",", "").Replace("}]", "").Split(new string[] { "\"" }, StringSplitOptions.RemoveEmptyEntries);
    }
    #endregion

    #region == ShowAlertMessage(클라이언트 ext 메시지 박스 띄우기) ==

    private void ShowAlertMessage(string pTitle, string pMessage)
    {
        X.Msg.Alert(pTitle, pMessage, new JFunction { Fn = "showResult" }).Show();
    }

    private void ShowYesNoMessage(string pTitle, string pMessage, object sender, string pProjCd, string pDt, string pGubun)
    {
        X.Msg.Show(new MessageBoxConfig
        {
            Title = pTitle,
            Message = pMessage,
            Buttons = MessageBox.Button.YESNO,
            Icon = MessageBox.Icon.QUESTION,
            Fn = new JFunction { Fn = pGubun == "C" ? "showResultYesno" : "showResultYesnoD", Args = new string[] { pProjCd, pDt } },
            AnimEl = (sender is Button)? (sender as Button).ClientID : string.Empty
        });
    }


    #endregion





    #region == popup 모음 ==

    protected void btnChoiceAdd_Click(object sender, DirectEventArgs e)
    {
        var win = new Window
        {
            ID = "Window1",
            //Title = "My Window",
            Height = 400,
            Width = 800,
            Padding = 5,
            Modal=true
        };


        Button btn = (Button)sender;
        string id = btn.ID;
        string json = e.ExtraParams["Values"];
        string strPath = CreatePath(json, id);


        switch (id)
        {
            case "btnAddPeople":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "인원 현황 추가항목";
                break;

            case "btnAddMat":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "자재 현황 추가항목";
                break;

            case "btnAddEqp":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "장비 현황 추가항목";
                break;

            case "btnAddPlan":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "공종 계획 불러오기";
                break;

            case "btnAddTrans":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "운송 현황 추가항목";
                break;

            case "btnAddCost":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "경비 현황 추가항목";
                break;

            case "btnOutSourcing":
                win.Listeners.Hide.Handler = "btnAddPeople.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "외주 관리 추가항목";
                break;

                //2012.01.14 박승한 - 권한승인 팝업 추가
            case "btnConfirmView":
                win.Listeners.Hide.Handler = "btnConfirmView.setDisabled(false);";
                win.AutoLoad.Url = strPath;
                win.Title = "수정요청 조회/승인";
                break;
                

            default:
                break;
        }

        win.AutoLoad.Mode = LoadMode.IFrame;
        win.Render(this.Form);
    }

    private string CreatePath(string json, string id)
    {
        string strNotIn = string.Empty;
        string strPath = string.Empty;

        if ((id.Equals("btnAddPeople") || id.Equals("btnAddTrans")) && !string.IsNullOrEmpty(json))
        {
            Dictionary<string, string>[] dicValues = JSON.Deserialize<Dictionary<string, string>[]>(json);

            foreach (Dictionary<string, string> dic in dicValues)
            {
                foreach (KeyValuePair<string, string> row in dic)
                {
                    switch (id)
                    {
                        case "btnAddPeople":
                            if (row.Key.Equals("ID"))
                            {
                                if (!string.IsNullOrEmpty(row.Value))
                                    strNotIn += "'" + row.Value + "',";

                            }
                            break;

                        case "btnAddTrans":
                            if (row.Key.Equals("ID"))
                            {
                                if (!string.IsNullOrEmpty(row.Value))
                                    strNotIn += "'" + row.Value + "',";

                            }
                            break;

                        default:
                            break;

                    }
                }
            }
        }


        if (!string.IsNullOrEmpty(strNotIn))
            strNotIn = "( " + strNotIn.Remove(strNotIn.Length - 1) + " )";


        switch (id)
        {
            case "btnAddPeople":
                strPath = "Popup/Popup_People1.aspx?Prj_CD=" + this.hdnPROJ_CD.Text + "&DT=" + this.hdnDT.Text + "&NotIn=" + strNotIn;
                break;

            case "btnAddMat":
                switch (cbxAddMat.SelectedItem.Value)
                {
                    case "A":
                        strPath = "Popup/Popup_Mat1.aspx";
                        break;
                    case "B":
                        strPath = "Popup/Popup_Mat2.aspx";
                        break;
                    case "C":
                        strPath = "Popup/Popup_Mat3.aspx";
                        break;
                    case "D":
                        strPath = "Popup/Popup_Mat4.aspx";
                        break;
                    default:
                        break;
                }
                break;

            case "btnAddEqp":
                switch (cbxAddEqp.SelectedItem.Value)
                {
                    case "A":
                        strPath = "Popup/Popup_Eqp1.aspx";
                        break;
                    case "B":
                        strPath = "Popup/Popup_Eqp2.aspx";
                        break;
                    default:
                        break;
                }
                break;

            case "btnAddPlan":
                strPath = "Popup/Popup_Plan1.aspx?NotIn=" + strNotIn;
                break;

            case "btnAddTrans":
                switch (cbxAddTrans.SelectedItem.Value)
                {
                    case "A":
                        strPath = "Popup/Popup_Trans1.aspx?NotIn=" + strNotIn;
                        break;
                    case "B":
                        strPath = "Popup/Popup_Trans2.aspx?NotIn=" + strNotIn;
                        break;
                    default:
                        break;
                }
                break;

            case "btnAddCost":
                //임시주석처리
                //switch (cbxAddCost.SelectedItem.Value)
                //{
                //    case "A":
                //        strPath = "Popup/Popup_Cost1.aspx";
                //        break;
                //    case "B":
                //        strPath = "Popup/Popup_Cost2.aspx";
                //        break;
                //    default:
                //        break;
                //}
                break;

            case "btnOutSourcing":
                strPath = "Popup/Popup_OutSourcing1.aspx?NotIn=" + strNotIn;
                break;


            //2012.01.14 박승한 - 권한승인 팝업 추가
            case "btnConfirmView":
                strPath = "Popup/Popup_Confirm.aspx";
                break;
                

            default:
                break;

        }

        return strPath;
    }

    #endregion

}
